use chrono::Utc;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::config::OpenAIConfig;
use crate::error::{AppError, AppResult};

#[derive(Debug, Serialize)]
struct AIRequest {
    model: String,
    messages: Vec<AIMessage>,
    temperature: f32,
}

#[derive(Debug, Serialize, Deserialize)]
struct AIMessage {
    role: String,
    content: String,
}

#[derive(Debug, Deserialize)]
struct AIResponse {
    choices: Vec<AIChoice>,
}

#[derive(Debug, Deserialize)]
struct AIChoice {
    message: AIMessage,
}

#[derive(Debug, Deserialize)]
pub struct PlanSuggestion {
    pub name: String,
    pub description: String,
    pub next_reminder: String,
    pub frequency: String,
}

pub struct AIService {
    client: Client,
    config: OpenAIConfig,
}

impl AIService {
    pub fn new(config: OpenAIConfig) -> Self {
        Self {
            client: Client::new(),
            config,
        }
    }
    
    /// 调用 AI 生成提醒计划
    pub async fn generate_plan(&self, user_message: &str) -> AppResult<String> {
        // 获取中国时间 (UTC+8)
        let china_time = Utc::now() + chrono::Duration::hours(8);
        let current_time = china_time.format("%Y-%m-%d %H:%M:%S CST").to_string();
        
        let system_prompt = format!(
            r#"你是一个智能提醒助手,帮助用户创建提醒计划。
当前时间: {}

请根据用户的输入,提取以下信息:
1. 提醒内容 (content)
2. 提醒时间 (reminder_time)
3. 提醒频率 (frequency: daily/weekly/monthly/yearly/once)

如果信息不完整,请用友好的语气询问用户。
如果信息完整,请以 JSON 格式返回计划(仅返回JSON,不要其他文字):
{{
  "name": "简短的计划名称",
  "description": "这里是直接发送给用户的提醒内容，要有情绪价值，温馨、鼓励或有趣，让用户感受到关怀",
  "next_reminder": "2025-11-03T15:00:00+08:00",
  "frequency": "once"
}}

重要说明:
1. next_reminder 必须使用中国时区格式 (+08:00),例如 "2025-11-03T15:00:00+08:00"
2. description 是直接发送给用户的提醒消息，不是对计划的描述！
   - 要有情绪价值，温馨、鼓励或有趣
   - 例如: "🌞 早安！别忘了今天的运动计划哦，坚持就是胜利！💪"
   - 例如: "💡 提醒：今天是您的重要会议，加油！您一定可以的！"
   - 例如: "🎂 生日快乐！今天是 TA 的生日，别忘记送上祝福哦～""#,
            current_time
        );
        
        let request = AIRequest {
            model: self.config.model.clone(),
            messages: vec![
                AIMessage {
                    role: "system".to_string(),
                    content: system_prompt,
                },
                AIMessage {
                    role: "user".to_string(),
                    content: user_message.to_string(),
                },
            ],
            temperature: 0.7,
        };
        
        let response = self
            .client
            .post(format!("{}/chat/completions", self.config.url))
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .map_err(|e| AppError::AIServiceError(format!("Failed to call AI API: {}", e)))?;
        
        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            return Err(AppError::AIServiceError(format!(
                "AI API returned error {}: {}",
                status, error_text
            )));
        }
        
        let ai_response: AIResponse = response
            .json()
            .await
            .map_err(|e| AppError::AIServiceError(format!("Failed to parse AI response: {}", e)))?;
        
        let ai_message = ai_response
            .choices
            .first()
            .ok_or_else(|| AppError::AIServiceError("No response from AI".to_string()))?
            .message
            .content
            .clone();
        
        Ok(ai_message)
    }
    
    /// 尝试解析 AI 响应为计划建议
    pub fn parse_plan_suggestion(&self, ai_response: &str) -> Option<PlanSuggestion> {
        // 尝试从响应中提取 JSON
        let json_start = ai_response.find('{')?;
        let json_end = ai_response.rfind('}')?;
        let json_str = &ai_response[json_start..=json_end];
        
        serde_json::from_str::<PlanSuggestion>(json_str).ok()
    }
}
